<template>
  <div class="map-container">
    <baidu-map
      v-if="state.baidu.ak && mapReady"
      v-loading="state.baidu.loading"
      :center="center"
      :zoom="zoom"
      @ready="handler"
      @click="getLocationPoint"
      :ak="state.baidu.ak"
      class="map"
      :scroll-wheel-zoom="true"
    >
      <bm-marker
        :position="markerPosition"
        :dragging="false"
        @click="infoWindowOpen"
      >
        <bm-info-window
          :show="show"
          @close="infoWindowClose"
          @open="infoWindowOpen"
        >
          <div class="info-window-content">
            <div>{{ points.address }}</div>
            <div style="margin-top: 10px;">{{ points.organName }}</div>
          </div>
        </bm-info-window>
      </bm-marker>
    </baidu-map>
  </div>
</template>

<script setup name="BaiduMap">
import { BaiduMap, BmMarker, BmInfoWindow } from "vue-baidu-map-3x";
import { ref, onMounted, nextTick, reactive, watch } from "vue";

const props = defineProps({
  ak: {
    type: String,
    default: "",
    required: true,
  },
  points: {
    type: Object,
  },
});

const center = ref({ ...props.points });
const zoom = ref(15);
const mapReady = ref(false);
const markerPosition = ref({ ...props.points });

const state = reactive({
  baidu: {
    loading: true,
    map: null,
    BMap: null,
    ak: props.ak,
  },
});

// 确保DOM完全加载后再初始化地图
onMounted(() => {
  nextTick(() => {
    mapReady.value = true;
  });
});

const handler = ({ BMap, map }) => {
  state.baidu.BMap = BMap;
  state.baidu.map = map;
  state.baidu.loading = false;
  // 设置中心点和标记位置
  const point = new BMap.Point(props.points.lng, props.points.lat);
  map.centerAndZoom(point, zoom.value);
  // 强制重绘地图
  nextTick(() => {
    setTimeout(() => {
      map.checkResize();
      center.value = { ...props.points };
      markerPosition.value = { ...props.points };
    }, 100);
  });
};

// 监听props.points变化
watch(
  () => props.points,
  (newVal) => {
    if (state.baidu.map && newVal) {
      const point = new state.baidu.BMap.Point(newVal.lng, newVal.lat);
      state.baidu.map.setCenter(point);
      center.value = { ...newVal };
      markerPosition.value = { ...newVal };
    }
  },
  { deep: true }
);

const getLocationPoint = (e) => {
  // 点击地图获取坐标的逻辑
};

const show = ref(true);

const infoWindowClose = () => {
  show.value = false;
};
const infoWindowOpen = () => {
  show.value = true;
};
</script>

<style lang="scss" scoped>
.map-container {
  width: 100%;
  height: 100%;
  .map {
    width: 100%;
    height: 400px;
    // min-height: 400px; // 确保有最小高度
    .info-window-content {
      text-align: center; /* 文本居中 */
      white-space: pre-line; /* 保留换行符并自动换行 */
      word-break: break-all; /* 长单词或URL强制换行 */
      max-width: 200px; /* 可选：限制宽度以强制换行 */
    }
  }
}

:deep(.BMap_cpyCtrl),
:deep(.anchorBL) {
  display: none !important;
  background: transparent;
}
</style>
